<template>
  <div class="appointment-list-container">
    <el-card shadow="never" class="mb-6 border-box">
      <el-form :inline="true" :model="queryParams" class="flex flex-wrap items-end h-[40px]">
        <el-form-item label="预约状态">
          <el-select
            v-model="statusFilter"
            placeholder="全部状态"
            clearable
            style="width: 180px"
          >
            <el-option label="待支付" :value="1" />
            <el-option label="已预约" :value="2" />
            <el-option label="已取消" :value="3" />
            <el-option label="已核销" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约类型">
          <el-select
            v-model="typeFilter"
            placeholder="全部类型"
            clearable
            style="width: 180px"
          >
            <el-option label="个人" :value="1" />
            <el-option label="团体" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-date-picker
            v-model="reserveTime"
            type="date"
            placeholder="选择预约日期"
            format="YYYY-MM-DD"
            value-format="YYYYMMDD"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <div class="flex gap-2">
            <el-button type="primary" @click="handleSearch" :icon="Search"> 查询 </el-button>
            <el-button @click="resetQuery" :icon="Refresh"> 重置 </el-button>
            <el-button type="success" @click="handleExport" :icon="Download"> 导出 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    
    <div class="page-content appointment-list">
      <el-table
        v-loading="isLoading"
        :data="appointmentList"
        class="w-full"
        v-if="!showEmpty"
        height="calc(100vh - 328px)"
      >
        <el-table-column prop="touristUser.userName" label="用户姓名" min-width="120" />
        <el-table-column prop="touristUser.userPhone" label="联系方式" min-width="130" />
        <el-table-column prop="scenicSpotVo.spotName" label="景点名称" min-width="150" />
        <el-table-column prop="orderType" label="预约类型" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.orderType === 1" type="primary">个人</el-tag>
            <el-tag v-else-if="scope.row.orderType === 2" type="success">团体</el-tag>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="预约状态" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.orderStatus === 1" type="warning">待支付</el-tag>
            <el-tag v-else-if="scope.row.orderStatus === 2" type="success">已预约</el-tag>
            <el-tag v-else-if="scope.row.orderStatus === 3" type="danger">已取消</el-tag>
            <el-tag v-else-if="scope.row.orderStatus === 4" type="info">已核销</el-tag>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="reserveTime" label="预约时间" min-width="150">
          <template #default="scope">
            {{ scope.row.reserveTime ? useDateFormat(scope.row.reserveTime, 'YYYY-MM-DD') : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="150">
          <template #default="scope">
            {{ scope.row.createTime ? useDateFormat(scope.row.createTime, 'YYYY-MM-DD HH:mm:ss') : '' }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200px">
          <template #default="scope">
            <el-row>
              <el-button
                type="primary"
                text
                size="small"
                link
                @click="showDetailDialog(scope.row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <!-- <el-button
                v-if="scope.row.orderStatus === 2"
                type="danger"
                text
                size="small"
                link
                @click="handleCancelOrder(scope.row)"
              >
                <el-icon><Close /></el-icon>
                取消预约
              </el-button> -->
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div class="flex justify-center h-[calc(100vh-328px)]" v-if="showEmpty">
        <el-empty description="暂无预约数据" />
      </div>

      <!-- 分页器 -->
      <div class="flex justify-center mt-5">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 预约详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="预约详情" width="60%">
      <div v-if="currentAppointment" class="appointment-detail">
        <el-descriptions :column="2" border>
          {{currentAppointment}}
          <el-descriptions-item label="用户姓名">{{ currentAppointment.touristUser.userName}}</el-descriptions-item>
          <el-descriptions-item label="联系方式">{{ currentAppointment.touristUser.userPhone}}</el-descriptions-item>
          <el-descriptions-item label="景点名称">{{ currentAppointment.scenicSpotVo?.spotName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="预约类型">
            <el-tag v-if="currentAppointment.orderType === 1" type="primary">个人</el-tag>
            <el-tag v-else-if="currentAppointment.orderType === 2" type="success">团体</el-tag>
            <span v-else>未知</span>
          </el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag v-if="currentAppointment.orderStatus === 1" type="warning">待支付</el-tag>
            <el-tag v-else-if="currentAppointment.orderStatus === 2" type="success">已预约</el-tag>
            <el-tag v-else-if="currentAppointment.orderStatus === 3" type="danger">已取消</el-tag>
            <el-tag v-else-if="currentAppointment.orderStatus === 4" type="info">已核销</el-tag>
            <span v-else>未知</span>
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ currentAppointment.reserveTime ? useDateFormat(currentAppointment.reserveTime, 'YYYY-MM-DD') : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentAppointment.createTime ? useDateFormat(currentAppointment.createTime, 'YYYY-MM-DD HH:mm:ss') : '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 预约人员详情 -->
        <div v-if="currentAppointment.reserveDetailVoList && currentAppointment.reserveDetailVoList.length > 0" class="mt-4">
          <h4>预约人员详情</h4>
          <el-table :data="currentAppointment.reserveDetailVoList" class="mt-2">
            <el-table-column prop="realName" label="姓名" min-width="120" />
            <el-table-column prop="mobile" label="手机号" min-width="130" />
            <el-table-column prop="idCard" label="身份证号" min-width="180" />
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
                <el-tag v-else-if="scope.row.status === 0" type="danger">已取消</el-tag>
                <span v-else>未知</span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="150" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { Search, View, Close, Refresh, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDateFormat } from '@vueuse/core'
import { ReserveOrderVo } from '@/api/4a/types'
import {
  scenicReserveOrderQueryPageOrderUsingPost,
  scenicReserveOrderCancelOrderUsingPost,
  scenicReserveOrderExportOrderUsingPost
} from '@/api/4a/yuyueguanli'

const appointmentList = ref<ReserveOrderVo[]>([])
const total = ref(0)
const isLoading = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const statusFilter = ref<number | undefined>()
const typeFilter = ref<number | undefined>()
const reserveTime = ref<string | undefined>(undefined)
const detailDialogVisible = ref(false)
const currentAppointment = ref<ReserveOrderVo | null>(null)

// 查询参数
const queryParams = reactive({
  orderStatus: statusFilter,
  orderType: typeFilter,
  reserveTime: reserveTime
})

// 请求参数
const requestParams = computed(() => {
  return {
    current: currentPage.value,
    size: pageSize.value,
    orderStatus: statusFilter.value,
    orderType: typeFilter.value,
    reserveTime: reserveTime.value
  }
})

// 获取预约列表
const getAppointmentList = async () => {
  isLoading.value = true
  try {
    const res = await scenicReserveOrderQueryPageOrderUsingPost({
      body: requestParams.value
    })
    if (res.code === 0) {
      appointmentList.value = res.data?.list || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error(res.msg || '获取预约列表失败')
    }
  } catch (error: any) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  } finally {
    isLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getAppointmentList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getAppointmentList()
}

// 查询预约
const handleSearch = () => {
  currentPage.value = 1
  getAppointmentList()
}

// 重置查询
const resetQuery = () => {
  statusFilter.value = undefined
  typeFilter.value = undefined
  reserveTime.value = undefined
  currentPage.value = 1
  getAppointmentList()
}

// 显示详情对话框
const showDetailDialog = (row: ReserveOrderVo) => {
  currentAppointment.value = row
  detailDialogVisible.value = true
}

// 取消预约
const handleCancelOrder = async (row: ReserveOrderVo) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个预约吗？',
      '取消预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await scenicReserveOrderCancelOrderUsingPost({
      params: { orderId: row.id! }
    })
    
    if (res.code === 0) {
      ElMessage.success('取消预约成功')
      getAppointmentList() // 刷新列表
    } else {
      ElMessage.error(res.msg || '取消预约失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败')
    }
  }
}

// 导出预约数据
const handleExport = async () => {
  try {
    ElMessage.info('正在导出数据，请稍候...')
    
    const exportParams = {
      orderStatus: statusFilter.value,
      orderType: typeFilter.value,
      reserveTime: reserveTime.value,
      current: 1,
      size: 10000
    }
    
    // 使用fetch直接请求，避免axios拦截器处理二进制数据
    const apiBaseUrl = import.meta.env.VITE_API_URL || ''
    const response = await fetch(`${apiBaseUrl}/scenic/reserveOrder/exportOrder`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('accessToken') || ''
      },
      body: JSON.stringify(exportParams)
    })
    
    if (response.ok) {
      // 获取响应头中的Content-Type
      const contentType = response.headers.get('content-type') || ''
      
      // 检查是否是Excel文件
      if (contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || 
          contentType.includes('application/octet-stream') ||
          contentType.includes('application/vnd.ms-excel')) {
        
        // 直接获取二进制数据
        const blob = await response.blob()
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `预约数据_${new Date().toISOString().slice(0, 10)}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('导出成功')
      } else {
        // 如果不是文件，尝试解析为JSON
        const result = await response.json()
        if (result.code === 0) {
          ElMessage.success('导出成功')
        } else {
          ElMessage.error(result.msg || '导出失败')
        }
      }
    } else {
      // 处理错误响应
      try {
        const errorData = await response.json()
        ElMessage.error(errorData.msg || '导出失败')
      } catch {
        ElMessage.error('导出失败，服务器返回错误')
      }
    }
  } catch (error: any) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + (error.message || '网络错误'))
  }
}

// 空状态判断
const showEmpty = computed(() => {
  return appointmentList.value.length === 0 && !isLoading.value
})

onMounted(() => {
  getAppointmentList()
})
</script>

<style lang="scss" scoped>
.appointment-list-container {
  min-height: calc(100vh - 121px);
}


.page-content {
  .appointment-detail {
    .mt-4 {
      margin-top: 16px;
    }
    
    .mt-2 {
      margin-top: 8px;
    }
    
    h4 {
      margin: 0 0 8px 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}

:deep(.el-table) {
  .el-table__header {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }
}

:deep(.el-pagination) {
  .el-pagination__total {
    color: #606266;
  }
}
</style>
